﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Messaging;
using System.Threading;

using Ncqrs.EventSourcing.EntityFramework;

using TheKitchen.Querying.Core.DataAccess;

namespace TheKitchen.Setup
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Creating the event store database...");
            var eventStoreContext = new EventStoreContext();
            if (!eventStoreContext.DatabaseExists())
            {
                eventStoreContext.CreateDatabase();
            }

            Console.WriteLine("Creating the query store database...");

            var queryContext = new QueryContext();
            if (!queryContext.DatabaseExists())
            {
                queryContext.CreateDatabase();
            }

            Console.WriteLine("Creating the outgoing event queue...");
            CreatePrivateQueue("TheKitchenOutgoingEventsQueue");

            Console.WriteLine("Creating the incoming event queue...");
            CreatePrivateQueue("TheKitchenIncomingEventsQueue");
        }

        private static void CreatePrivateQueue(string name)
        {
            string fullQueueName = @".\private$\" + name;

            if (!MessageQueue.Exists(fullQueueName))
            {
                MessageQueue queue = MessageQueue.Create(fullQueueName, true);
                
                var permissions = new AccessControlList
                {
                    new MessageQueueAccessControlEntry(
                        new Trustee(Thread.CurrentPrincipal.Identity.Name),
                        MessageQueueAccessRights.FullControl, AccessControlEntryType.Set)
                };

                queue.SetPermissions(permissions);
            }
        }
    }
}